package com.tbit.uqbike.service.business.impl;

import com.alibaba.fastjson.JSON;
import com.tbit.common.utils.TbitHttpServiceUtil;
import com.tbit.uqbike.constant.BrandRemoteConfigConstant;
import com.tbit.uqbike.object.pojo.BrandRemoteConfig;
import com.tbit.uqbike.object.pojo.SmsAuthConfig;
import com.tbit.uqbike.object.pojo.vo.SendPhoneVo;
import com.tbit.uqbike.object.view.FollowDTO;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.service.business.SensitivenessService;
import com.tbit.uqbike.webmanager.dao.core.AccountDao;
import com.tbit.uqbike.webmanager.dao.core.SensitivenessDao;
import com.tbit.uqbike.webmanager.dao.core.SmsAuthConfigDao;
import com.tbit.uqbike.webmanager.dao.log.SensitivenessLogDao;
import com.tbit.uqbike.webmanager.sms.ApiStoreMsgUtils;
import com.tbit.uqbike.webmanager.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author LHX
 * @Date 2023/11/16 10:17
 */
@Service
@Slf4j
public class SensitivenessServiceImpl implements SensitivenessService {


	@Resource
	private SensitivenessDao sensitivenessDao;

	@Resource
	private SmsAuthConfigDao smsAuthConfigDao;

	@Resource
	private SensitivenessLogDao sensitivenessLogDao;
	@Resource
	private SmsAuthConfigServiceImpl smsAuthConfigService;
	@Resource
	private AccountDao accountDao;


	/**
	 * 关注或取消关注
	 * @param followDTO followDTO
	 * @return result
	 */
	@Override
	public Result<String> follow(FollowDTO followDTO) {
		Assert.notNull(followDTO.getAccountId(), "区域id为null");
		Assert.notNull(followDTO.getAccountUserId(), "账户id为null");
		Assert.notNull(followDTO.getType(), "敏感操作类型为null");
		Assert.notNull(followDTO.getStatus(), "状态为null");
		//判断本次操作是关注还是取关
		try {
			if (followDTO.getStatus() == 1) {
				//关注
				sensitivenessDao.follow(followDTO);
			} else if (followDTO.getStatus() == 2) {
				//取关
				sensitivenessDao.uncheck(followDTO);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error();
		}
		return Result.success();
	}

	/**
	 * 是否关注
	 * @param followDTO followDTO
	 * @return boolean
	 */
	@Override
	public Result<Boolean> getSens(FollowDTO followDTO) {
		Assert.notNull(followDTO.getAccountId(), "区域id为null");
		Assert.notNull(followDTO.getAccountUserId(), "账户id为null");
		Assert.notNull(followDTO.getType(), "敏感操作类型为null");
		int count = sensitivenessDao.getSens(followDTO);
		return Result.success(count > 0);
	}


	/**
	 * 发送短信通知
	 * @param accountId 区域id
	 * @param type      敏感操作类型(1:计费规则 2:系统配置)
	 */
	public void sendMessage(Integer accountId, Integer type) {
		try {
			//需要通知手机号
			List<SendPhoneVo> list = sensitivenessDao.sendPhone(accountId, type);
			if (list != null && list.size() > 0) {
				SendPhoneVo sendPhoneVo = list.get(0);
				SmsAuthConfig smsAuthConfig = smsAuthConfigDao.getByAccountId(sendPhoneVo.getBrandId());
				//优驱api配置
				Integer brandId = accountDao.getBrandIdByAccountIdV2(accountId);
				BrandRemoteConfig brandRemoteConfigDB = smsAuthConfigService.getBrandRemoteConfig(brandId, BrandRemoteConfigConstant.TBIT_CONFIG);
				if (smsAuthConfig != null && smsAuthConfig.getFrom() == 0) {
					for (SendPhoneVo phoneVo : list) {
						if (Objects.nonNull(brandRemoteConfigDB)){
							String templateId = smsAuthConfigService.getBrandRemoteConfigValue(brandId, BrandRemoteConfigConstant.SMS_OPERATION_NOTIFY);
							if (StringUtils.isNotBlank(templateId)){
								//优驱api发送短信
								String key = brandRemoteConfigDB.getParamKV();
								String[] strings = key.split("&");
								Map<String,Object> map = new HashMap<>();
								map.put("accountName", phoneVo.getAccountName());
								if (phoneVo.getType() == 1) {
									map.put("config", "计费规则");
								} else if (phoneVo.getType() == 2) {
									map.put("config", "系统配置");
								}
								boolean result = TbitHttpServiceUtil.sendSms(strings[0].substring(strings[0].indexOf("=") + 1),
										strings[1].substring(strings[1].indexOf("=") + 1)
										, strings[2].substring(strings[2].indexOf("=") + 1), phoneVo.getPhone(), JSON.toJSONString(map), Integer.valueOf(templateId));
								phoneVo.setMessage(templateId);
								if (!result) {
									log.info("手机号：{}优惠券到账提醒优驱api短信发送失败", phoneVo.getPhone());
								}
							}else {
								log.info("优惠券赠送短信发送失败，未配置短信模板id");
							}
						}else {
							/**构造短信内容*/
							String content = "";
							if (phoneVo.getType() == 1) {
								content = String.format("【%s-%s】计费规则变动", phoneVo.getBrandName(), phoneVo.getAccountName());
							} else if (phoneVo.getType() == 2) {
								content = String.format("【%s-%s】系统配置变动", phoneVo.getBrandName(), phoneVo.getAccountName());
							}
							ApiStoreMsgUtils.sendContent(phoneVo.getPhone(), smsAuthConfig.getSmsCodeKey(), content);
							phoneVo.setMessage(content);
						}
						//构造发送日志
						phoneVo.setSendTime(new Date());

					}
				}
				//插入发送日志
				sensitivenessLogDao.addLog(list);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			log.error("发送短信失败,区域id:{},类型:{}", accountId, type);
		}
	}
}
